using System;
using System.Collections.Generic;
using System.Text;
using Payton.WP7.Common.Model;
using Payton.WP7.Common;

namespace QWeiboSDK
{
    public delegate void AsyncRequestCallback(int key, string content);

    class CallbackInfo
    {
        public int key = 0;
        public AsyncRequestCallback callback = null;
    }

    public class QWeiboRequest
    {
        private Dictionary<AsyncHttp, CallbackInfo> asyncRquestMap = new Dictionary<AsyncHttp, CallbackInfo>();
        private int key = 0;

        //
        public bool BeginAsyncPost(string url, string httpMethod, OauthKey key, List<SNSParameter> listParam, List<SNSParameter> listFile,
            AsyncRequestCallback callback, out int callbkey, SNSProviderType provider = SNSProviderType.Unknow)
        {
            Oauth oauth = new Oauth();

            string queryString = null;
            string oauthUrl = oauth.GetOauthUrl(url, httpMethod, key.customKey, key.customSecret,
                key.tokenKey, key.tokenSecret, key.verify, key.callbackUrl, listParam, out queryString, provider);

            AsyncHttp http = new AsyncHttp();

            callbkey = GetKey();
            CallbackInfo callbackInfo = new CallbackInfo();
            callbackInfo.key = callbkey;
            callbackInfo.callback = callback;

            asyncRquestMap.Add(http, callbackInfo);

            bool bResult = false;

            if ((listFile == null) || (listFile.Count == 0))
            {
                bResult = http.HttpPost(oauthUrl, queryString, new AsyncHttpCallback(HttpCallback));
            }
            else
            {
                //if (provider == SNSProviderType.RenRen)
                //    bResult = http.HttpPostWithFile(oauthUrl, queryString, listFile, new AsyncHttpCallback(HttpCallback), listParam);
                //else
                bResult = http.HttpPostWithFile(oauthUrl + "?" + queryString, queryString, listFile, new AsyncHttpCallback(HttpCallback));
        
            }

            if (!bResult)
            {
                asyncRquestMap.Remove(http);
            }
            return bResult;
        }

        //
        protected void HttpCallback(AsyncHttp http, string content)
        {
            CallbackInfo info;
            if (!asyncRquestMap.TryGetValue(http, out info))
            {
                return;
            }

            if ((info != null) && (info.callback != null))
            {
                info.callback(info.key, content);
            }
            asyncRquestMap.Remove(http);
        }

        private int GetKey()
        {
            return ++key;
        }
    }
}
